<?php

namespace app\common\utils\manager;

use app\common\model\Uploadify;
use app\common\model\UploadifyCate;
use Exception;
use League\Flysystem\Filesystem;
use Overtrue\Flysystem\Qiniu\QiniuAdapter;

class QiniuManager
{
    private $factory;

    /**
     * 构造函数
     */
    public function __construct()
    {
        $accessKey = 'AT7XsTEMKzcZQ3Upidd9LHq8rrPSRnasNLt4bE48';
        $secretKey = 'pLh9KmM31Sx6Jmy6_NbdXFLiktkyi0MtjryyDQys';
        $bucket = 'hpadmin-shop';
        $domain = 'http://qnshop.hangpu.net'; // or with protocol: https://xxxx.bkt.clouddn.com

        $adapter = new QiniuAdapter($accessKey, $secretKey, $bucket, $domain);
        $flysystem = new Filesystem($adapter);
        $this->factory = $flysystem;
    }

    /**
     * 上传文件至七牛云
     *
     * @param string $filePath 上传的文件地址
     * @param string $saveName 保存文件名称
     * @param string $dir_name 分类目录名
     * @return boolean
     */
    public function upload(string $filePath, string $saveName, string $dir_name): bool
    {
        $category = UploadifyCate::where(['dir_name' => $dir_name])->find();
        if (!$category) {
            throw new Exception('找不到分类目录');
        }
        $size = filesize($filePath);
        $fileName = basename($saveName);
        $extension = substr(strrchr($saveName, '.'), 1);
        $stream = fopen($filePath, 'r+');
        // 获得七牛云配置
        $qiniu = $this->factory;
        // 检测文件是否存在
        if ($qiniu->fileExists($saveName)) {
            return true;
        }
        // 上传文件
        $qiniu->writeStream($saveName, $stream);
        fclose($stream);
        // 记录上传
        $uploadModel            = new Uploadify;
        $uploadModel->cid       = $category->id;
        $uploadModel->format    = $extension;
        $uploadModel->size      = get_size($size);
        $uploadModel->path      = $saveName;
        $uploadModel->title     = $fileName;
        if ($uploadModel->save()) {
            return true;
        }
        return false;
    }
}
